package com.rs.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rs.dao.ClassDao;
import com.rs.dao.ExamStudentRelationDAO;
import com.rs.entity.*;
import com.rs.entity.Class;
import com.rs.entity.excel.StudentExcelEntity;
import com.rs.service.ClassService;
import com.rs.service.ExamWorkService;
import com.rs.service.StudentService;
import com.rs.service.TermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author dehang
 * @date 2019/06/01
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private TermService termService;
    @Autowired
    private ExamWorkService examWorkService;
    @Autowired
    private ClassService classService;

    @RequestMapping("/index")
    public String index(Model model) {
        return "student/index";
    }


    @RequestMapping("/getTerms")
    @ResponseBody
    public Response<List<Term>> getTerms() {
        List<Term> terms=termService.list("");
        return Response.success(terms);
    }

    @RequestMapping("/list")
    @ResponseBody
    public Response list(long page, long limit,String name) {

        List<Student> classes = studentService.getStudentList(page,limit,name);
        return Response.list(classes,studentService.getStudentSum(name));
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        return "student/add";
    }

    @RequestMapping("/add")
    @ResponseBody
    public long addClass(String name, String no,String phone,String email,String gender) {
        //判断学号是否重复
        return studentService.addStudent(name,no,phone,email,gender);
    }


    @RequestMapping("/toUpdate")
    public String toUpload(Model model,int id) {
        Student student=studentService.getById(id);
        model.addAttribute("s",student);
        return "student/update";
    }

    @RequestMapping("/update")
    @ResponseBody
    public long updateClass(Integer id, String name, String no,String phone,String email,String gender) {

        return studentService.updateStudent(id, name,no,phone,email,gender);
    }

    @RequestMapping("/del")
    @ResponseBody
    public void delClass(long id) {

        studentService.delStudent(id);
    }


    @RequestMapping("/uploadStudents")
    @ResponseBody
    public Response test(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        List<StudentExcelEntity> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), StudentExcelEntity.class, params);
        String str=studentService.uploadSave(list);
        return Response.success(str);
    }


    @RequestMapping("/getExamWork")
    @ResponseBody
    public Response getExamWork(HttpServletRequest request, Integer type) throws Exception {

        Object user = request.getSession().getAttribute("user");
        if (user == null || !(user instanceof Student)) {
            return Response.fail("无权限");
        }
        Student student = (Student)user;
        ImportParams params = new ImportParams();
        // 从登录信息中获取用户学号
        String studentNo = student.getStudentNo();

        // 根据学号查询 examwork。
        List<ExamWork> examWorks = examWorkService.getInfoByStudentNoAndType(studentNo, type);

//        List<StudentExcelEntity> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), StudentExcelEntity.class, params);
//        studentService.uploadSave(list);
        return Response.success(examWorks);
    }


    @RequestMapping("/selectExam")
    public String selectExam(HttpServletRequest request,Model model ,Integer id){

        //查询当前考试
        ExamWork examWork=examWorkService.getOne(id);
        //查询文件url地址
        Student student = (Student)request.getSession().getAttribute("user");
        String url=examWorkService.getDownUrl(id,student.getStudentNo());
        model.addAttribute("exam",examWork);
        model.addAttribute("url",url);

        return "student/stu/exam";
    }


    /**
     * 上传作业
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadWork")
    @ResponseBody
    public Response<String> uploadWork(HttpServletRequest request,
                                       @RequestParam("file") MultipartFile file,
                                       @RequestParam("examId") Integer examId) throws IOException {

        Student student = (Student)request.getSession().getAttribute("user");
        // 获取课程编号
        String classNo = getClassNo(examId);
        // 目录：课程编号+考试id
        // 文件名：课程编号+考试id+学号.rar/zip
        // 业务文件存储路径
        String businessFilePath = classNo+"_"+examId;

        if(!file.isEmpty()){
            //可以对user做一些操作如存入数据库
            //以下的代码是将文件file重新命名并存入Tomcat的webapps目录下项目的下级目录fileDir
            String fileRealName = file.getOriginalFilename();                   //获得原始文件名;
            int pointIndex =  fileRealName.indexOf(".");                        //点号的位置
            String fileSuffix = fileRealName.substring(pointIndex);             //截取文件后缀

            String realPath = request.getSession().getServletContext().getRealPath(""); //获取服务器指定文件存取路径
            System.err.println(realPath);
            String savePath = realPath+"/upload/"+businessFilePath;
            String saveName = businessFilePath+"_"+student.getStudentNo()+fileSuffix;
            String resultPath = "/upload/"+businessFilePath+"/"+businessFilePath+"_"+student.getStudentNo()+fileSuffix;

            File file1 = new File(savePath);
            if (!file1.exists()) {
                file1.mkdir();
            }

            File savedFile = new File(savePath, saveName);
            boolean isCreateSuccess = savedFile.createNewFile();
            if(isCreateSuccess){
                file.transferTo(savedFile);  //转存文件
            }
            examWorkService.updateLoginStatus(examId, student.getStudentNo(),resultPath);
            return Response.success(resultPath);
        }
        return Response.fail("上传失败！");
    }

    /**
     * 校验作业密码
     * @return
     * @throws IOException
     */
    @RequestMapping("/verifyPassword")
    @ResponseBody
    public Response<String> verifyPassword(HttpServletRequest request, @RequestParam("id") Integer examId, @RequestParam("password") String password) throws IOException {
        Student student = (Student)request.getSession().getAttribute("user");
        String ip = getIp(request);
        ExamWork one = examWorkService.getOne(examId);
        if (one != null && one.getRemark3().equals(password)) {
            examWorkService.updateLoginInfo(examId, student.getStudentNo(), ip);
            return Response.success("成功");
        }
        return Response.fail("密码错误");
    }



    /**
     * 获取用户ip地址
     * @return
     */
    public static String getIp(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * 根据考试id获取课程编号
     * @param examId
     * @return
     */
    private String getClassNo(Integer examId) {
        // examId 查询 考试表 remark1（课程id）
        ExamWork one = examWorkService.getOne(examId);
        // 课程id
        String classId = one.getRemark1();
        // 根据课程id，查询class表 remark字段 得到课程编号。
        Class aClass = classService.getOne(Integer.valueOf(classId));
        // 课程编号
        String remark = aClass.getRemark();

        return remark;
    }
}
